<template>
  <!-- 直播管理 -->
  <a-spin class="live-review" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l search-box">
        <div>
          <span>站点：</span>
          <a-select
            allowClear
            style="width:160px;"
            showSearch
            :defaultActiveFirstOption="false"
            :filterOption="false"
            @search="getAllStation($event)"
            @change="changeLocation"
            v-model="search.locationId"
            placeholder="请选择站点"
            class="filter-select"
          >
            <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span>产品ID：</span>
          <a-input-search oninput="value = value.replace(/[^\d]/g, '')" style="width:240px;" placeholder="输入产品ID" allowClear v-model="search.productId" @search="handleByQueryCond" />
        </div>
        <div>
          <span>产品名称：</span>
          <a-input-search type="text" style="width:240px;" placeholder="输入产品名称" allowClear v-model="search.productName" @search="handleByQueryCond" />
        </div>
      </div>
      <div class="r">
        <a-button type="primary" style="margin-right:10px;background:#1d6fe9" @click="addProductVisible = true">新增产品</a-button>
      </div>
      <div class="r">
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body">
      <a-table :columns="tableColumns" :pagination="false" :data-source="dyLiveProductList" :scroll="{ x: 900, y: tableHeight }" rowKey="id">
        <template slot="urls" slot-scope="text, record">
          <template v-if="record.urls && record.urls.length > 0">
            <div>
              <upload v-show="record.urls && record.urls.length > 0" :limit="record.urls.length" disabled :value="record.urls"> </upload>
            </div>
          </template>
          <template v-else>
            无
          </template>
        </template>
        <!-- 产品佣金 -->
        <template slot="commission" slot-scope="text, record">
          <div>大达人:{{ record.superFirstMoney }}.{{ record.firstMoney }}</div>
          <div>小达人:{{ record.secondMoney }}</div>
        </template>
        <!-- 操作按钮 -->
        <template slot="action" slot-scope="text, record">
          <a-button v-if="record.isDelete === 1" type="link" herf="javascript:;" size="small" @click="showUp(record.id)">上架</a-button>
          <a-button v-if="record.isDelete === 0" type="link" herf="javascript:;" size="small" @click="showDown(record.id)">下架</a-button>
          <br />
          <a-button type="link" herf="javascript:;" size="small" @click="handleOpenSort(record.id, record.sequence)">排序</a-button>
          <br />
          <a-button type="link" herf="javascript:;" size="small" @click="handleOpenCommission(record.id, record.superFirstMoney, record.firstMoney, record.secondMoney)">佣金设置</a-button>
          <br />
          <a-button type="link" herf="javascript:;" size="small" @click="showPlacedTop(record.id)">置顶</a-button>
        </template>
      </a-table>
    </div>

    <!-- 新增产品弹窗 -->
    <a-modal v-model="addProductVisible" title="新增产品" @ok="handleAddProduct" @cancel="addClose">
      <a-form-model :model="addProductForm" ref="addProductForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item label="站点" prop="locationId" :rules="[{ required: true, trigger: 'change', message: '请选择站点' }]">
          <a-select allowClear showSearch :defaultActiveFirstOption="false" :filterOption="false" @search="getAllStation($event)" v-model="addProductForm.locationId" placeholder="请选择站点">
            <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="产品Id" prop="productId" :rules="[{ required: true, trigger: 'change', message: '请填写产品id' }]">
          <a-input allowClear oninput="value = value.replace(/[^\d]/g, '')" v-model="addProductForm.productId" />
        </a-form-model-item>
        <a-form-model-item label="产品图片" prop="pictureUrl" :rules="[{ required: true, trigger: 'blur', message: '请上传产品图片' }]">
          <upload :limit="1" v-model="addProductForm.pictureUrl" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 排序弹窗 -->
    <a-modal v-model="sortingVisible" title="修改排序" @ok="handleSort">
      <a-form-model ref="sortForm" :model="sortForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-model-item label="当前排序" prop="sequence" :rules="[{ required: true, message: '排序不能为空', trigger: 'change' }]">
          <a-input allowClear oninput="value = value.replace(/[^\d]/g, '')" v-model="sortForm.sequence" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 佣金设置弹窗 -->
    <a-modal v-model="commissionVisible" title="佣金设置" @ok="handleCommission">
      <a-form-model ref="commissionForm" :model="commissionForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-model-item label="大中达人佣金" prop="bigMoneyStr" :rules="[{ required: true, message: '大中达人佣金不能为空', trigger: 'change' }]">
          <a-input v-model="commissionForm.bigMoneyStr" />
        </a-form-model-item>
        <a-form-model-item label="小达人佣金" prop="secondMoney" :rules="[{ required: true, message: '小达人佣金不能为空', trigger: 'change' }]">
          <a-input v-model="commissionForm.secondMoney" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="pagination.pageSize"
        v-model="pagination.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
  </a-spin>
</template>

<script>
import { getCommonApiSearch, getLiveProductList, fixLiveProduct, topLiveProduct, addLiveProduct, fixLiveProductMoney } from '@/service'
import upload from '@/components/upload/upload'
import moment from 'moment'
import debounce from 'lodash/debounce'
import { getToken } from '@/util/method'
export default {
  name: 'dyLiveProductList',
  data() {
    // 节流
    this.getAllStation = debounce(this.getAllStation, 800)
    return {
      moment,
      headers: {
        Authorization: getToken()
      },
      //   新增产品弹窗状态
      addProductVisible: false,
      addProductForm: {
        locationId: null,
        productId: null,
        pictureUrl: []
      },
      //   排序弹窗状态
      sortingVisible: false,
      sortForm: {
        id: null,
        sequence: null
      },
      //   佣金弹窗状态
      commissionVisible: false,
      commissionForm: {
        liveId: null,
        bigMoneyStr: null,
        secondMoney: null
      },
      // loading是否显示
      isLoading: false,
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // 全部站点
      allStation: [],
      // table数据查询条件
      search: {
        locationId: '', // 站点id
        productId: null, // 产品id
        productName: '' // 产品名称
      },
      // 订单列表
      dyLiveProductList: [],
      tableColumns: [
        { title: '产品ID', width: 76, dataIndex: 'bizProductId' },
        { title: '产品名称', width: 140, dataIndex: 'bizProductName', scopedSlots: { customRender: 'cpName' } },
        { title: '产品排序', width: 140, dataIndex: 'sequence' },
        { title: '产品佣金', width: 140, scopedSlots: { customRender: 'commission' } },
        { title: '操作', width: 100, dataIndex: 'action', scopedSlots: { customRender: 'action' } }
      ]
    }
  },

  components: {
    upload
  },

  methods: {
    //   新增产品
    handleAddProduct() {
      this.$refs.addProductForm.validate(async (valid) => {
        if (valid) {
          let { locationId, productId, pictureUrl } = this.addProductForm
          let res = await addLiveProduct({ locationId, productId, pictureUrl: pictureUrl[0] })
          console.log(res)
          this.initQuery()
          this.addProductVisible = false
        } else {
          return false
        }
      })
    },
    // 关闭新增弹窗
    addClose() {
      this.addProductForm = {
        locationId: null,
        productId: null,
        pictureUrl: []
      }
      this.getAllStation()
      this.$refs.addProductForm.resetFields()
    },
    // 打开修改弹窗
    handleOpenSort(id, sequence) {
      this.sortingVisible = true
      this.sortForm = { id, sequence }
    },
    // 修改排序
    handleSort() {
      this.$refs.sortForm.validate(async (valid) => {
        if (valid) {
          let res = await fixLiveProduct(this.sortForm)
          console.log(res)
          this.initQuery()
          this.sortingVisible = false
        } else {
          return false
        }
      })
    },
    // 打开佣金
    handleOpenCommission(id, superFirstMoney, firstMoney, secondMoney) {
      this.commissionVisible = true
      this.commissionForm = { liveId: id, bigMoneyStr: superFirstMoney + '.' + firstMoney, secondMoney }
    },
    // 修改佣金
    handleCommission() {
      this.$refs.commissionForm.validate(async (valid) => {
        if (valid) {
          let res = await fixLiveProductMoney(this.commissionForm)
          console.log(res)
          this.initQuery()
          this.commissionVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },

    getAllStation(e) {
      getCommonApiSearch({ keywords: e }).then((res) => {
        this.allStation = res
      })
    },
    // 选择了站点
    changeLocation() {
      this.initQuery()
    },
    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { locationId, productId, productName } = this.search

      return {
        pageIndex,
        pageSize,
        locationId,
        productId,
        productName
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, productId, productName } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          productId: productId || '',
          productName: productName || ''
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },
    /**
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      getLiveProductList(this.getParams())
        .then((rs) => {
          console.log(rs)
          this.dyLiveProductList = Object.freeze(rs.dyLiveProductList) || []
          this.pagination.total = rs.total || 0
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    async showUp(id) {
      await fixLiveProduct({ id: id, isDelete: 0 })
      this.initQuery()
    },
    async showDown(id) {
      await fixLiveProduct({ id: id, isDelete: 1 })
      this.initQuery()
    },
    async showPlacedTop(id) {
      await topLiveProduct({ liveId: id })
      this.initQuery()
    }
  },

  mounted() {
    this.setSearch()

    // 获取所有站点
    getCommonApiSearch()
      .then((res = []) => {
        this.allStation = res
      })
      // 获取失败依然继续请求列表数据
      .catch((err) => err)

    this.initQuery()
  }
}
</script>

<style lang="less" scoped>
.live-review {
  padding: 16px;
}
// /deep/ .ant-upload-list-picture-card .ant-upload-list-item,
// /deep/ .ant-upload-list-picture-card-container {
//   width: 50px;
//   height: 50px;
//   margin: 0;
//   margin-right: 3px;
// }

.color-f55 {
  color: #f55f4e !important;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}
.multi-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; // 超出两行则以...形式隐藏
  -webkit-box-orient: vertical;
}
.ztDis_box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.zt_discrible_btn {
  color: #0090ff;
  cursor: pointer;
}

.zt_discrible_solution_list {
  list-style: none;
}
</style>
